package com.lvkerry.orderfood.service.impl;


import com.lvkerry.orderfood.api.ApiBean;
import com.lvkerry.orderfood.entity.UserEntity;
import com.lvkerry.orderfood.repository.UserRepository;
import com.lvkerry.orderfood.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import static com.lvkerry.orderfood.global.ConstCodeKt.API_ERROR;
import static com.lvkerry.orderfood.global.ConstCodeKt.API_SUCCESS;

/**
 * @author Kerry
 */

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    public ApiBean getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserEntity one = userRepository.findByUsername(authentication.getName());
        one.setPassword(null);
        return new ApiBean.Builder().setStatus(API_SUCCESS).setData(one).build();
    }

    @Override
    public ApiBean updatePassword(String newPw1, String newPw2) {
        if (newPw1.equals(newPw2)) {

            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

            String encode = passwordEncoder.encode(newPw1);
            UserEntity byUsername = userRepository.findByUsername(authentication.getName());
            byUsername.setPassword(encode);
            userRepository.save(byUsername);
            return new ApiBean.Builder().setStatus(API_SUCCESS).setMessage("更新成功").build();
        }
        return new ApiBean.Builder().setStatus(API_ERROR).setMessage("两次密码不一样...").build();
    }
}
